package com.civil.response;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Date;

import javax.imageio.ImageIO;

import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

@Component
public class ImgUtils {
	 private static final String[] IMAGE_TYPE = new String[] {".jpg",".png" };
	 
	 private static final Logger LOGGER = LoggerFactory.getLogger(ImgUtils.class);
	 
		public static PicUploadResult tpsupload(MultipartFile multipartFile,String url,String location){ 
	    	// 校验图片格式
	        boolean isLegal = false; 
	    	
	    	System.out.println(multipartFile.getOriginalFilename());
	    	for (String type : IMAGE_TYPE) { 
	        	
	            if (StringUtils.endsWithIgnoreCase(multipartFile.getOriginalFilename(), type)) {
	                isLegal = true;
	                break;
	            }
	        } 
	    	
	    	 // 封装Result对象，并且将文件的byte数组放置到result对象中
	    	 PicUploadResult fileUploadResult = new PicUploadResult();
	    	 
	         fileUploadResult.setCode(isLegal ? 0 : 1); 
	    	 String filePath = getFilePath(multipartFile.getOriginalFilename(),url);
	         System.out.println(multipartFile.getOriginalFilename());
	         if (LOGGER.isDebugEnabled()) {
	        	 System.out.println(LOGGER.isDebugEnabled());
	             LOGGER.debug("Pic file upload .[{}] to [{}] .", multipartFile.getOriginalFilename(), filePath);
	         }
	         System.out.println(filePath);
	          
	      // 生成图片的绝对引用地址/usr/src/img/    /zuanshi/shop-upload
	         String picUrl = StringUtils.replace(StringUtils.substringAfter(filePath, url),"\\", "/");
	         System.out.println("对引用地址"+picUrl);
	         fileUploadResult.setUrl(picUrl);

	         File newFile = new File(filePath);
	          multipartFile.getOriginalFilename();
	         
	         // 写文件到磁盘
	          try {
				multipartFile.transferTo(newFile);
			} catch (IllegalStateException e1) {
				e1.printStackTrace();
			} catch (IOException e1) {
				e1.printStackTrace();
			} 
	         // 校验图片是否合法
	         isLegal = false;
	         try {
	             BufferedImage image = ImageIO.read(newFile);
	             if (image != null) {
	            	 System.out.println(image.getWidth());
	                 fileUploadResult.setWidth(image.getWidth() + "");
	                 fileUploadResult.setHeight(image.getHeight() + "");
	                 isLegal = true;
	             }
	         } catch (IOException e) {
	         }

	         // 状态
	         fileUploadResult.setCode(isLegal ? 0 : 1);

	         if (!isLegal) {
	             // 不合法，将磁盘上的文件删除
	             newFile.delete();
	         } 
	         
	         return fileUploadResult;
	    }
	    
	     //F:\\img
	    private static String getFilePath(String sourceFileName,String url) {
	        String baseFolder =url + File.separator + "img";
	        Date nowDate = new Date();
	        // yyyy/MM/dd
	        String fileFolder = baseFolder + File.separator + new DateTime(nowDate).toString("yyyy")
	                + File.separator + new DateTime(nowDate).toString("MM") + File.separator
	                + new DateTime(nowDate).toString("dd");
	        
	        File file = new File(baseFolder);
	        if (!file.isDirectory()) {
	            // 如果目录不存在，则创建目录
	            file.mkdirs();
	        }
	        // 生成新的文件名
	        String fileName = new DateTime(nowDate).toString("yyyyMMddhhmmssSSSS")
	                + RandomUtils.nextInt(100, 9999) + "." + StringUtils.substringAfterLast(sourceFileName, ".");
	        return baseFolder + File.separator + fileName;
	    }
	    
	    
	    public static String getFilePathUrl(String sourceFileName) {
	        Date nowDate = new Date();
	        // yyyy/MM/dd
	        String fileFolder = "img" + File.separator + new DateTime(nowDate).toString("yyyy")
	                + File.separator + new DateTime(nowDate).toString("MM") + File.separator
	                + new DateTime(nowDate).toString("dd"); 
	        // 生成新的文件名
	        String fileName = new DateTime(nowDate).toString("yyyyMMddhhmmssSSSS")
	                + RandomUtils.nextInt(100, 9999)+ "." + StringUtils.substringAfterLast(sourceFileName, ".");
	        return fileFolder + "," + fileName;
	    }
 
	    
	    
	    public static void main(String[] args) {
		}
	    

}
